package de.gameduell.framework.queue {
	import flash.events.EventDispatcher;

	/**
	 * @author ddoe
	 */
	public class ChainedAction extends EventDispatcher implements IGDAction {
		
		private var actions:Array;
		private var _actionQueue:GDActionQueue;
		private var _isComputing:Boolean;

		public function ChainedAction(aActions:Array = null,invokeNow:Boolean = false) {
			if(aActions != null){
				actions = aActions;
			}else{
				actions = new Array();
			}
			_actionQueue = GDActionQueue.getInstance();		
			if(invokeNow){
				invoke();
			}
		}
		
		public function add(action:IGDAction):void {
			actions.push(action);					
		}	
		
		public function onActionDone(event:ActionEvent = null):void{
			actions.shift();
			compute();
		}

		private function registerForEvents():void {
			for (var i in actions) {
				actions[i].addEventListener(ActionEvent.DONE, onActionDone);			
			}
		}
		
		private function unRegisterForEvents():void {
			for (var i in actions) {
				actions[i].removeEventListener(ActionEvent.DONE, onActionDone);			
			}
		}
	
		public function compute():void {	
			if(actions.length > 0){
				_isComputing = true;
				registerForEvents();
				IGDAction(actions[0]).compute();
			}else{
				unRegisterForEvents();
				_isComputing = false;
				dispatchEvent(new ActionEvent(ActionEvent.DONE));
			}
		}
		
		public function invoke():void {
			_actionQueue.add(this);
		}
		
		public function get description():String {
			var description:String = "";
			for each(var action:IGDAction in actions){
				description = description+ "\n"+action.description;
			}
			return description;
		}
		
		public function get isComputing():Boolean{
			return _isComputing;
		}
	}
}
